package com.shenchuangit.rydemo.web.leaveappr.controller;

import com.ruoyi.activiti.enumation.BusinessStatusEnum;
import com.ruoyi.activiti.utils.WorkflowHelper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.shenchuangit.rydemo.web.leaveappr.domain.LeaveApplication;
import com.shenchuangit.rydemo.web.leaveappr.service.ILeaveApplicationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 请假申请Controller
 *
 * @author liuyu
 * @date 2022-01-07
 */
@RestController
@RequestMapping("/leave/application")
@Api(tags = "请假申请")
public class LeaveApplicationController extends BaseController {

    @Autowired
    private ILeaveApplicationService leaveApplicationService;
    @Autowired
    private WorkflowHelper workflowHelper;

    public static final String PROCESS_DEFINITION_KEY = "leave_application";

    /**
     * 查询请假申请列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询请假申请列表")
    public TableDataInfo list(LeaveApplication leaveApplication) {
        startPage();
        List<LeaveApplication> list = leaveApplicationService.selectLeaveApplicationList(leaveApplication);
        return getDataTable(list);
    }

    /**
     * 导出请假申请列表
     */
    @Log(title = "请假申请", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ApiOperation(value = "导出请假申请列表")
    public AjaxResult export(LeaveApplication leaveApplication) {
        List<LeaveApplication> list = leaveApplicationService.selectLeaveApplicationList(leaveApplication);
        ExcelUtil<LeaveApplication> util = new ExcelUtil<LeaveApplication>(LeaveApplication.class);
        return util.exportExcel(list, "leaveApplication");
    }

    /**
     * 获取请假申请详细信息
     */
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取请假申请详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(leaveApplicationService.selectLeaveApplicationById(id));
    }

    /**
     * 新增请假申请
     */
    @RepeatSubmit
    @Log(title = "请假申请", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增请假申请")
    public AjaxResult add(@RequestBody LeaveApplication leaveApplication) {
        leaveApplication.setStatus(BusinessStatusEnum.NOT_SUBMIT.toString());
        return toAjax(leaveApplicationService.insertLeaveApplication(leaveApplication));
    }

    /**
     * 修改请假申请
     */
    @RepeatSubmit
    @Log(title = "请假申请", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改请假申请")
    public AjaxResult edit(@RequestBody LeaveApplication leaveApplication) {
        return toAjax(leaveApplicationService.updateLeaveApplication(leaveApplication));
    }

    /**
     * 删除请假申请
     */
    @RepeatSubmit
    @Log(title = "请假申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除请假申请")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(leaveApplicationService.deleteLeaveApplicationByIds(ids));
    }

    /**
     * 提交租后检查
     */
    @Log(title = "请假申请", businessType = BusinessType.UPDATE)
    @PostMapping("/submit")
    @RepeatSubmit
    @ApiOperation(value = "提交")
    public AjaxResult submit(@RequestBody LeaveApplication afterRentCheck) {
        return toAjax(leaveApplicationService.submit(afterRentCheck));
    }

    /**
     * 查询代办列表
     */
    @GetMapping("/applyList")
    @ApiOperation(value = "查询待办列表")
    public TableDataInfo applyList(LeaveApplication base) {
        TaskQuery taskQuery = this.workflowHelper.initTaskQuery(PROCESS_DEFINITION_KEY);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<Task> approvalTaskPage = this.workflowHelper.getApprovalTaskPage(taskQuery, pageDomain);

        String username = SecurityUtils.getLoginUser().getUsername();
        List<LeaveApplication> list = new ArrayList<>();
        for (Task task : approvalTaskPage.getContent()) {
            LeaveApplication fromDb = this.leaveApplicationService.selectByInstanceId(task.getProcessInstanceId());
            fromDb.setTaskId(task.getId());
            if (null != task.getAssignee()) {
                fromDb.setAssignee(task.getAssignee());
            }
            fromDb.setHandleState(username.equals(task.getAssignee()));
            list.add(fromDb);
        }

        return new TableDataInfo(list, (int) approvalTaskPage.getTotalElements());
    }

    /**
     * 查询审批记录列表
     * @return 审批记录历史
     */
    @GetMapping("/approvalRecordList")
    @ApiOperation(value = "查询审批记录列表")
    public TableDataInfo clearApprovalRecordList() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Page<HistoricTaskInstance> historicTaskInstancePage = this.workflowHelper.getApprovalRecordPage(PROCESS_DEFINITION_KEY, pageDomain);
        List<LeaveApplication> list = this.leaveApplicationService.selectByHistoricTaskInstancePage(historicTaskInstancePage);
        Page<LeaveApplication> page = new PageImpl<>(list, historicTaskInstancePage.getPageable(), historicTaskInstancePage.getTotalElements());
        return new TableDataInfo(list, (int) page.getTotalElements());
    }
}
